package com.springboot2.controller;

import com.springboot2.entity.Product;
import com.springboot2.service.ProductService;
import com.springboot2.utils.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/product/")
public class ProductController {

    @Resource
    private ProductService productService;

    //增
    @PostMapping("add")
    public Result save(@RequestBody Product product){
        productService.add(product);
        return Result.success();
    }
    //删
    @DeleteMapping("del/{id}")
    public Result del(@PathVariable int id){
        productService.del(id);
        return Result.success();
    }
    //改
    @PutMapping("update")
    public Result update(@RequestBody Product product){
        productService.update(product);
        return Result.success();
    }
    //获取对象
    @GetMapping("find/{id}")
    public Result findById(@PathVariable int id){
        return Result.success(productService.findById(id));
    }
    //分页列表
    @GetMapping("list/{pageNo}/{pageSize}")
    public Result findByPage(@PathVariable int pageNo,@PathVariable int pageSize){
        Map<String,Object> map= new HashMap<>();
        map.put("data",productService.findByPage(pageNo, pageSize));
        map.put("total",productService.count());
        return Result.success(map);
    }

    //分页列表
    @GetMapping("findByList")
    public Result findByList(@RequestParam(required = false,defaultValue = "0",value = "pageNo") int pageNo,
                             @RequestParam(required = false,defaultValue = "10",value = "pageSize") int pageSize){
        Map<String,Object> map= new HashMap<>();
        map.put("data",productService.findByPage(pageNo, pageSize));
        map.put("total",productService.count());
        return Result.success(map);
    }

    //查询条件
    @GetMapping("listParams/{pageNo}/{pageSize}/{name}")
    public Result findByPageParams(@PathVariable int pageNo,@PathVariable int pageSize,@PathVariable String name){
        Map<String,Object> map= new HashMap<>();
        map.put("data",productService.findByPageParams(pageNo, pageSize, name));
        map.put("total",productService.countParams());
        return Result.success(map);
    }
    //批量删除
    @DeleteMapping("batch/{ids}")
    public Result dels(@PathVariable String ids){
        String[] splits = ids.split(",");
        for (String s:splits){
            productService.del(Integer.parseInt(s));
        }
        return Result.success();
    }
}
